// Node.js Stream(流)

// 从流中读取数据
const fs = require('fs');
let data = '';

//-------------------------------------
// 创建可读流
let readStream = fs.createReadStream('./static/input.txt');
readStream.setEncoding('utf8');

// 处理流事件 --> data, end, and error
readStream.on('data', (datas) => {
    data += datas
});

readStream.on('end', ()=> {
    console.log(data)
});

readStream.on('error', (err)=>{
    console.log(err.stack)
});

console.log("程序执行完毕");

// ------------------------------------
// 写入流
let data1 = '菜鸟教程真的是好的一批';
let writeStream = fs.createWriteStream('./static/output.txt');

// 使用 utf8 编码写入数据
writeStream.write(data1, 'utf8');

// 标记文件末尾
writeStream.end();

// 处理流事件 --> data, end, and error
writeStream.on('finish', () => {
    console.log("写入完成。");
});

writeStream.on('error', (err) => {
    console.log(err.stack)
});

console.log("写入流程序执行完毕");


// -----------------------------------------------
// 管道流

// 创建一个可读流
let readerStream = fs.createReadStream('./static/input.txt');
// 创建一个可写流
let writerStream = fs.createWriteStream('./static/opt.txt');

// 管道读写操作
// 读取 input.txt 文件内容，并将内容写入到 output.txt 文件中
readerStream.pipe(writerStream);

console.log("管道流程序执行完毕");

// --------------------
// 链式流
let zlib = require('zlib');

fs.createReadStream('./static/input.txt')
    .pipe(zlib.createGzip())
    .pipe(fs.createWriteStream('./static/input.txt.gz'));
console.log('文件压缩完成！！');